﻿#include "JZJsonHelper.h"

bool JZJsonHelper::getValue(const QJsonValue &in_value, const QString &path, QJsonValue &value)
{
    QStringList parts = path.split('.');
    QJsonValue currentValue = in_value;
    for(int i = 0; i < parts.size(); i++)
    {
        QString part = parts[i];
        int bracketIndex = part.indexOf('[');
        
        QString name;
        if (bracketIndex == -1)
            name = part;
        else if(bracketIndex > 0)
            name = part.left(bracketIndex);

        if (!name.isEmpty())
        {
            if (!currentValue.isObject())
                return false;

            auto obj = currentValue.toObject();
            if (!obj.contains(name))
                return false;
            currentValue = obj[name];
        }

        if (bracketIndex != -1)
        {
            if (!currentValue.isArray())
                return false;

            int closingBracketIndex = part.indexOf(']', bracketIndex);
            if (closingBracketIndex == -1)
                return false;

            QString indexStr = part.mid(bracketIndex + 1, closingBracketIndex - bracketIndex - 1);
            bool ok;
            int arrayIndex = indexStr.toInt(&ok);
            if (!ok)
                return false;

            auto array = currentValue.toArray();
            if (arrayIndex >= 0 && arrayIndex < array.size()) {
                currentValue = array[arrayIndex];
            }
            else {
                return false;
            }
        }            
    }
    
    value = currentValue;
    return true;
}